package com.dg11185.nearshop.activity.home.actys;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.AsyncHttpResponseHandler;
import com.dg11185.libs.ormlite.android.apptools.OpenHelperManager;
import com.dg11185.libs.ormlite.dao.Dao;
import com.dg11185.libs.utils.date.DateUtils;
import com.dg11185.libs.utils.print.PrintUtils;
import com.dg11185.nearshop.activity.home.NewActysAdapter;
import com.dg11185.nearshop.activity.home.WebviewActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.ViewUtils;
import com.dg11185.nearshop.dbHelper.OrmLiteHelper;
import com.dg11185.nearshop.net.request.GetActivityListRequest;
import com.dg11185.nearshop.net.response.GetActivityListResponse;
import com.dg11185.nearshop.net.response.NetStatus;
import com.dg11185.nearshop.net.weixin.Tabloid;
import com.dg11185.nearshop.net.weixin.TabloidRequest;
import com.dg11185.nearshop.net.weixin.TabloidResponse;

/**
 * 首页活动部分功能
 * 
 * @author：Daibo
 * @time：2014-8-22 下午3:35:38
 */
public class NewActysHelper {

    private Activity mActivity = null;

    private ViewStub newestActivitiesView;// 最新活动

    private GridView newestActivities;// 商家类型快捷入口和最新活动视图

    /** 数据库 */
    private OrmLiteHelper databaseHelper = null;// 底包数据库helper

    private Dao<Tabloid, Integer> tabloidDao = null;

    private AnimationDrawable mTabloidAnim = null;

    public NewActysHelper(Activity activity) {
        this.mActivity = activity;
    }

    /**
     * 获取服务器最新的小报消息，有数据更新就刷新顶栏的TabloidBtn，并将小报数据插入到数据库
     */
    public void initTabloidData(final AnimationDrawable anim) {

        this.mTabloidAnim = anim;
        String time = "";
        try {
            tabloidDao = getHelper().getTabloidDao();
            Tabloid tabloid = tabloidDao.queryForFirst(tabloidDao.queryBuilder().orderBy("id", false).prepare());
            if (tabloid == null) {
                time = DateUtils.dayMove(DateUtils.getCurrentDate(), -60);
            } else {
                time = tabloid.createTime;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        TabloidRequest request = new TabloidRequest(time, "0");
        NetClient.client.get(mActivity, request.getUrl(), new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                TabloidResponse result = new TabloidResponse();
                result.parseJson(new String(responseBody));
                if (result.tabloids.size() != 0) {
                    // 有新小报数据，更新界面 插入数据库
                    mTabloidAnim.start();

                    try {
                        for (int a = 0; a < result.tabloids.size(); a++) {
                            tabloidDao.create(result.tabloids.get(a));
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            }
        });
    }

    // 初始化活动部分view
    public void initNewActysView(final View view) {

        newestActivitiesView = (ViewStub) view.findViewById(R.id.view_newest_activities);
        newestActivities = (GridView) view.findViewById(R.id.grid_v_newest_activities);
        GetActivityListRequest request = new GetActivityListRequest(Constants.AREA_NUM).encryption();
        request.setActionListener(new GetActivityListRequest.ActionListener<GetActivityListResponse>() {

            @Override
            public void onSuccess(GetActivityListResponse result) {
                if (result.status == NetStatus.SUCCESS) {
                    if (result.activities.size() > 0) {
                        showNewestActyView(view, result.activities);
                    }
                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                    ViewUtils.showToast(mActivity, R.string.cant_connect_network);
                } else {
                    ViewUtils.showToast(mActivity, R.string.network_error);
                }

            }
        });
        NetClient.httpGet(request);

        // showNewestActyView(view, null);

    }

    /**
     * 显示最新活动视图。日后要根据接口数据决定是否要显示
     * 
     */
    private void showNewestActyView(View parentView, final List<com.dg11185.nearshop.net.entity.Activity> activities) {
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        for (com.dg11185.nearshop.net.entity.Activity a : activities) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("imageUrl", a.midPhotoUrl);
            data.add(map);
        }
        newestActivitiesView.setVisibility(View.VISIBLE);
        newestActivities = (GridView) parentView.findViewById(R.id.grid_v_newest_activities);
        newestActivities.setAdapter(new NewActysAdapter(mActivity, data, R.layout.view_activities_grid_v_item,
                new String[] { "imageUrl" }, new int[] { R.id.image_v_activities_item }));
        newestActivities.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // *******点击活动的事件添加**********//
                Intent intent = new Intent(mActivity, WebviewActivity.class);
                intent.putExtra("webviewUrl", activities.get(position).url);
                mActivity.startActivity(intent);
            }
        });
    }

    /**
     * 检查是否还有未读取的小报消息
     * 
     * @return false 不存在， true 存在 
     */
    public void setTabloidBtnState(){

        PrintUtils.printo("setTabloidBtnState had benn start");
        if(mTabloidAnim == null){
            return;
        }
        
        try {
            tabloidDao = getHelper().getTabloidDao();
            Tabloid tabloid = tabloidDao.queryForFirst(tabloidDao.queryBuilder().orderBy("id", false).prepare());
            if(tabloid == null){
                mTabloidAnim.stop();
            }else{
                if(tabloid.isReaded){
                    mTabloidAnim.stop();
                }else{
                    mTabloidAnim.start();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * You'll need this in your class to get the helper from the manager once
     * per class.
     */
    public OrmLiteHelper getHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(mActivity, OrmLiteHelper.class);
        }
        return databaseHelper;
    }

    public void releseDBHelper() {
        /*
         * You'll need this in your class to release the helper when done.
         */
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }

    }

}
